﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Dycox.Workflows.Manipulation;

namespace Dycox.Workflows
{
    public class AbortProcessOperation : ProcessOperation
    {
        public AbortProcessOperation(string reason)
        {
            this.Reason = reason;
        }

        private string _reason;

        public string Reason
        {
            get { return _reason; }
            set
            {
                if (string.IsNullOrWhiteSpace(value))
                    throw new WorkflowException("Must provide the reason of process abortion.");

                _reason = value;
            }
        }

        protected override void PerformCore(WFProcess process, TransitionOperationArguments args)
        {
            OperationArguments args1 = new OperationArguments(new ProcessAbortingContract(_reason), args.Context.Arguments.DataSource);
            Workflow wf;

            args1.UserData.OperatorName = args.Context.Arguments.OperatorName;

            if (process == args.Context.Process)
            {
                wf = Transition.Workflow;
                //.Control.AbortProcess(args.Context, _reason);
                args1.ComponentID = args.Context.Step.ID;
            }
            else
            {
                wf = args.Context.Workflow;
                //.Control.AbortProcess(process, _reason);
                args1.ComponentID = process.ID;
            }

            using (AbortProcessContext context = new AbortProcessContext(wf, args1))
            {
                context.BeginExecute();
                wf.AbortProcess(context, false);
                context.EndExecute(false);
            }
        
        }

        public override TransitionTypes SupportedTransitionTypes
        {
            get { return TransitionTypes.NoMoreStep | TransitionTypes.ExitStage; }
        }
    }
}
